import { HttpRequestConfig, HttpResponse } from 'luch-request'

export default (app: any) => {
  const { $env } = app
  uni.$zz.http.setConfig((config: HttpRequestConfig) => {
    console.log(config, $env, 'config---env')
    config.baseURL = $env.BASE_URL /* 根域名 */
    return config
  })

  uni.$zz.http.interceptors.request.use(
    (config: HttpRequestConfig) => {
      const proxy = config?.custom?.proxy
      if (proxy) {
        config.baseURL = $env[proxy]
      }
      return config
    },
    (config: HttpRequestConfig) => Promise.reject(config)
  )

  uni.$zz.http.interceptors.response.use(
    (response: HttpResponse) => {
      const { data } = response
      // 自定义参数
      const custom = response?.config?.custom
      if (data.code !== 200) {
        console.log(custom, 'custom--------')
        if (custom?.toast) {
          uni.$tm.u.toast(data.message)
        }
        if (custom?.catch) {
          return Promise.reject(data)
        }
        return new Promise(() => {})
      }
      return data.data || {}
    },
    (response: HttpResponse) => Promise.reject(response)
  )
}
